class Nickname {
    constructor() {
        this.showNickname()

        // 注销事件
        this.$('.enter ul').children[1].addEventListener('click', this.cancel)
    }

    // 登录后显示昵称
    showNickname() {
        let nickname = localStorage.getItem('user_nickname')
        let token = localStorage.getItem('token')
        let cartLength = localStorage.getItem('cart')
        // console.log(cartLength);
        // console.log(nickname);

        if (!token) {
            return;
        } else {
            this.$('.enter ul').innerHTML = `<li>
            <a href="#">${nickname}</a>
            <span>|</span>
            </li>
            <li>
                <a href="#">注销</a>
                <span>|</span>
            </li>
            <li>
                <a href="#">消息通知</a>
            </li>`;

            this.$('.header_ri .shopcar').innerHTML = `<span>${cartLength}</span>
            购物车<em>(${cartLength})</em>`
        }
    }

    // 注销删除local storage
    cancel() {
        let Id = localStorage.getItem('user_id')
        // 设置编码方式
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

        // 发送ajax请求，注册
        let param = `id=${Id}`;
        axios.post('http://localhost:8888/users/logout/:id', param).then(() => {
            localStorage.clear();
            location.reload();
        })
    }

    // 获取节点的方法
    $(ele) {
        let res = document.querySelectorAll(ele);
        return res.length == 1 ? res[0] : res;
    }
}

new Nickname;